<template>
  <div class="treeCompositeTable" v-loading="loading">
    <el-container>
      <el-aside :width="leftWidth">
        <el-input
          :placeholder="$t('common.filter')"
          v-model="filterText"
          clearable
        >
        </el-input>
        <el-scrollbar class="scrollbarTree">
          <!-- :indent="8" -->
          <el-tree
            :data="data"
            :indent="8"
            :default-expand-all="defaultExpandAll"
            ref="tree"
            highlight-current
            :expand-on-click-node="false"
            check-on-click-node
            accordion
            node-key="id"
            :current-node-key="currentKey"
            :default-expanded-keys="expandedKeys"
            @node-click="handleNodeClick"
            :filter-node-method="filterNode"
            v-bind="$attrs"
            v-on="$listeners"
          >
            <template slot-scope="{ node, data }">
              <slot :data="{ node, data }">
                <span class="df-span">{{ node.label }}</span>
              </slot></template
            >
          </el-tree>
        </el-scrollbar>
      </el-aside>
      <el-main class="main-pack">
        <ele-page
          v-bind="$attrs"
          v-on="$listeners"
          ref="treeCompositeTable"
          :beforeAjax="beforeAjax"
          @handleReset="handleReset"
        >
        </ele-page>
      </el-main>
    </el-container>
  </div>
</template>

<script>
export default {
  name: "tree-composite-table",
  inheritAttrs: false,
  props: {
    leftWidth: {
      type: String,
      default: "200px",
    },
    //树形结构API
    treeApi: Function,
    //树形接口请求参数
    treeParams: {
      type: Object,
      default: () => ({}),
    },
    //树形数据转化
    tranformTreeData: Function,
    //查询子节点请求参数
    getParamsFromNode: {
      type: [ Object, Function ],
      default: () => {
        return {
          column: [],
        };
      },
    },
    defaultExpandAll: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      filterText: "",
      data: [],
      currentData: {}, //当前node数据
      requestParams: {}, //当前请求参数集合
      currentKey: null, //当前选中Id
      expandedKeys: [], //展开的ID
      loading: false,
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getTreeData();
  },
  methods: {
    //筛选过滤
    filterNode(value, data) {
      const { props } = this.$attrs;
      if (!value) return true;
      const label = props && props.label ? props.label : "label";
      return data[label].indexOf(value) !== -1;
    },
    //获取属性数据
    getTreeData() {
      if (!this.treeApi) {
        console.warn("请传入获取树形数据的API（treeApi）");
        return;
      }
      this.loading = true;
      this.treeApi(this.treeParams)
        .then((res) => {
          const data = this.tranformTreeData
            ? this.tranformTreeData(res)
            : res.data.result || [];
          this.data = data;
          this.$nextTick(() => {
            this.$refs['tree'].setCurrentKey(this.currentKey);
            this.$refs.tree.filter(this.filterText);
          })
        })
        .finally((res) => {
          this.loading = false;
        });
    },
    //节点选择事件
    handleNodeClick(data, node, self) {
      this.currentData = data;
      this.currentKey = data['id'];
      this.getChildrenParams(data);
      this.$refs.treeCompositeTable.refresh(true);
      this.$emit("node-select", { data, node, self });
    },
    //获取子节点请求参数
    getChildrenParams(data) {
      // 判断getParamsFromNode是否是函数，如果是函数进行执行
      if (typeof this.getParamsFromNode === 'function') {
        this.requestParams = this.getParamsFromNode(data);
      } else {
        const { column, ...reset } = this.getParamsFromNode; //getParamsFromNode
        const params = {};
        column.forEach(({ value, key }) => {
          const index = key ? key : value;
          params[index] = data[value];
        });
        this.requestParams = { ...params, ...reset };
      }
    },
    //请求表格之前的请求参数处理
    beforeAjax(params) {
      const data = { ...params, ...this.requestParams };
      return data;
    },
    handleReset() { 
      this.refresh(true);
    },
    //刷新树状数据，以及当前节点的详情
    /*
      @params  isReset 是否重新刷新
    */
    refresh(isReset = false) {
      if (isReset) {
        // this.currentData = {};
        // this.requestParams = {};
        // this.currentKey = null;
        // this.expandedKeys = [];
        this.$emit("node-select", {});
        this.getTreeData();
      }
      this.$refs.treeCompositeTable.refresh(true);
    },
  },
};
</script>

<style lang="scss" scoped>
.treeCompositeTable {
  //background-color: #eff2fb;
  padding: 0;
  //margin: -10px;
  min-height: calc(100vh - 112px);
  .el-main {
    padding: 10px;
    padding-top: 0;
  }
  .df-span {
    font-size: 14px;
  }
  .el-aside {
    background-color: #ffffff;
    padding: 10px;
    min-height: calc(100vh - 112px);
  }
  .scrollbarTree {
    height: calc(100vh - 170px);
    box-sizing: border-box;
    background-color: #ffffff;
    /deep/ .el-tree-node > .el-tree-node__children {
      overflow: inherit;
    }
  }

  .main-pack {
    width: calc(100vw - 365px);
    //height: calc(100vh - 122px);
    margin-left: 10px;
    background-color: white;
    padding: 10px;
    padding-bottom: 0;
  }
}
</style>
